package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ShopTypeMapper shopTypeMapper;

    @Override
    public Result querylist() {
        String key  = "shopTypelist";
        //1.查看缓存中有没有数据
        List<String> stringList = stringRedisTemplate.opsForList().range(key, 0, -1);
//        if (stringList != null) {
//            //2.缓存中有数据则返回
//            // List<String>  ===> List<?>
//            List<ShopType> shopTypeList = JSONUtil.toList(stringList.toString(), ShopType.class);
//            return Result.ok(shopTypeList);
//        }
        if(stringList.size() != 0 && stringList != null) {
            List<ShopType> typeList = new ArrayList<>();
            for (String shopType : stringList) {
                typeList.add(JSONUtil.toBean(shopType, ShopType.class));
            }
            return Result.ok(typeList);
        }
        //3.缓存中无数据则查询数据库
        List<ShopType> typeList = this.query().orderByAsc("sort").list();
        // 数据库未查到
        if (typeList == null) {
            // 6.不存在，返回错误信息
            return Result.fail("店铺类型不存在！");
        }
        List<String> stringnewList = new ArrayList<>();
        for (ShopType shopType : typeList) {
            stringnewList.add(JSONUtil.toJsonStr(shopType));
        }

        stringRedisTemplate.opsForList().rightPushAll(key, stringnewList);
        // 5.返回数据
        return Result.ok(typeList);
    }
}
